<template>
    <div class="container">
        <div class="top-container">
            <div class="left">
                <div v-if="imgBase" class="cropper-container">
                    <VueCropper ref="cropper" :img="imgBase" :canScale="false" :autoCrop="true" :fixed="true"
                        :canMove="false" :info="false" :fixedBox="true" outputType="jpeg" @realTime="realTimeHandle">
                    </VueCropper>
                </div>
                <el-upload v-show="!imgBase"  v-model:file-list="fileList" ref="upload"
                    action="http://localhost:5099/api/files/upload/formimg" :on-exceed="handleExceed"
                    :on-change="handleSelect" :on-success="handleSuccess" :on-error="handleError" name="files"
                    :auto-upload="false" :show-file-list="false" :limit="1">
                    <el-button :icon="Picture" size="large">选择图片</el-button>
                </el-upload>
            </div>
            <el-divider direction="vertical" style="height: 200px;width: 1px;" />
            <div class="right">
                <div class="preview">
                    <el-avatar :src="avatar" :size="60"></el-avatar>
                    <span>预览图片</span>
                </div>
            </div>
        </div>

        <div class="bottom-container">
            <el-button :disabled="submitDisabled" @click="submit">更新</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
    // 引入 vue-cropper
    import 'vue-cropper/dist/index.css';
    import { VueCropper } from 'vue-cropper';
    import { Picture } from "@element-plus/icons-vue"
    import { UploadInstance, UploadProps, UploadRawFile, genFileId,ElMessage } from "element-plus";
    import { computed, onMounted, reactive, ref } from 'vue';
    import loginapi from '../api/loginapi';

    // 获取保存事件
    const emit = defineEmits(["onSave"]);

    // 获取传入id
    const props = defineProps({
        id: {
            type: Number,
            required: true
        }
    });

    const { id } = props;
    let loginInfo = ref<any>({});
    const upload = ref<UploadInstance>();
    const imgBase = ref<string | ArrayBuffer | null>(null);
    const cropper = ref();
    const submitDisabled = ref(true)
    const fileList = ref<[]>([])


    // 预览头像
    const avatar = ref<string>("");

    // 获取用户信息
    loginapi.getByUser(id).then((res: any) => {
        loginInfo.value = res.data;
        avatar.value = `http://localhost:5099/wwwroot/images/${loginInfo.value.ProfilePhoto}`;
    });


    // 选中数量超出限制  
    const handleExceed: UploadProps['onExceed'] = (files) => {
        //保持一个文件
        upload.value!.clearFiles();
        const file = files[0] as UploadRawFile;
        file.uid = genFileId();
        console.log("file", file);

        upload.value!.handleStart(file)
    };

    // 文件选中事件
    const handleSelect: UploadProps['onChange'] = (file) => {
        submitDisabled.value = false;
        // 获取选中图片的base64
        const fr = new FileReader();
        fr.readAsDataURL(file.raw!);
        fr.onload = (e) => {
            imgBase.value = e.target!.result;
            avatar.value = imgBase.value?.toString()!;
        }
    }

    // 实时渲染事件
    const realTimeHandle = (data: any) => {
        // 截图
        cropper.value.startCrop();
        cropper.value.getCropData(data => {
            avatar.value = data
        });
    }

    // 上传事件
    const submit = () => {
        // base64 转 jpg
        var arr = avatar.value.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        
        // 替换要上传的文件
        let file = new File([u8arr],fileList.value[0].name,{type:mime});
        file.uid = fileList.value[0].uid;
        fileList.value[0].raw=file;
        
        // 上传
        upload.value?.submit();
    }

    // 上传成功
    const handleSuccess: UploadProps['onSuccess'] = (response) => {
        ElMessage.success({
            message:"上传成功"
        });

        // 获取上传成功的图片名称
        loginInfo.value.ProfilePhoto = response.data[0];

        // 修改登录信息
        loginapi.Update(loginInfo.value).then((res:any)=>{
          if(res.code==1){
            ElMessage.success({
                message:"修改成功"
            });
            emit("onSave");
          }
        });

    }

    const handleError: UploadProps['onError'] = (error) => {
        console.log(error);

    }

</script>

<style scoped>
    .top-container {
        height: 300px;
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 0 20px;
    }

    .top-container>div {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 200px;
    }

    .bottom-container {
        display: flex;
        justify-content: center;
    }

    .cropper-container {
        height: 200px;
        width: 150px;
    }

    .preview {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10px 0;
        font-size: 12px;
        color: #99a2bd;
    }

    .bottom-container>.el-button {
        width: 200px;
    }
</style>